package com.nerve.cloudoffice.web.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.nerve.util.RequestUtil;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.nerve.cloudoffice.common.Reply;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.service.CustomerService;
import com.nerve.cloudoffice.service.impl.CustomerServiceImpl;
import com.nerve.cloudoffice.web.model.CustomerModel;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class CustomerAction extends NerveAction implements ModelDriven<CustomerModel>{

	private CustomerModel model = new CustomerModel();
	private CustomerService service = new CustomerServiceImpl();
	
	public CustomerModel getModel() {
		return model;
	}
	
	public void list(){
		Reply re = new Reply();
		try{
			service.list(model);
			re.setMessage(model.getCustomerList());
		}catch(Exception e){
			e.printStackTrace();
			
			re.setError(true);
			re.setMessage(e);
		}
		
		json(re,new ValueFilter() {
			public Object process(Object arg0, String arg1, Object arg2) {
				if(arg1.equals("user")){
					if(arg2 == null)
						return arg2;
					
					User u = (User)arg2;
					return u.getName();
				}
				
				return arg2;
			}
		});
	}
	
	public void save(){
		Reply re = new Reply();
		
		try{
			model.getCustomer().setStartDate(buildDate());
			service.add(model);
			
			re.setMessage("SUCCESS");
		}catch(Exception e){
			re.error(e);
		}
		
		json(re);
	}
	
	public void update(){
		Reply re = new Reply();
		
		try{
			
			model.getCustomer().setStartDate(buildDate());
			service.update(model);
			
			re.setMessage("SUCCESS");
		}catch(Exception e){
			re.error(e);
			
			e.printStackTrace();
		}
		
		json(re);
	}
	
	private Date buildDate(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String dateString = RequestUtil.getString(request, "startDate");
		System.out.println("startDate==" + dateString);
		
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.parse(dateString);
		}catch(Exception e){
			return new Date();
		}
	}
}